package com.lbd.gulimall.member.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.lbd.common.to.GiteeSocialUser;
import com.lbd.gulimall.member.entity.MemberLevelEntity;
import com.lbd.gulimall.member.exception.PhoneExistException;
import com.lbd.gulimall.member.exception.UsernameExistException;
import com.lbd.gulimall.member.service.MemberLevelService;
import com.lbd.gulimall.member.vo.UserLoginVO;
import com.lbd.gulimall.member.vo.UserRegisterVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lbd.common.utils.PageUtils;
import com.lbd.common.utils.Query;

import com.lbd.gulimall.member.dao.MemberDao;
import com.lbd.gulimall.member.entity.MemberEntity;
import com.lbd.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {
    @Autowired
    private MemberLevelService memberLevelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(UserRegisterVO userRegisterVO) {
        MemberEntity memberEntity = new MemberEntity();
        List<MemberLevelEntity> memberLevelEntities = memberLevelService.list(new QueryWrapper<MemberLevelEntity>().eq("default_status", 1));
        Long levelId = memberLevelEntities.get(0).getId();
        memberEntity.setLevelId(levelId);
        checkExistUsername(userRegisterVO.getUserName());
        memberEntity.setUsername(userRegisterVO.getUserName());
        checkExistPhone(userRegisterVO.getPhone());
        memberEntity.setMobile(userRegisterVO.getPhone());
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(userRegisterVO.getPassword());
        memberEntity.setPassword(encode);
        memberEntity.setCreateTime(new Date());
        this.save(memberEntity);
    }

    @Override
    public MemberEntity login(UserLoginVO userLoginVO) {
        //用户名和手机号码唯一
        MemberEntity memberEntity = this.getOne(new QueryWrapper<MemberEntity>()
                .eq("username", userLoginVO.getUsername())
                .or()
                .eq("mobile", userLoginVO.getUsername()));
        if (memberEntity != null) {
            String secret = memberEntity.getPassword();
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            boolean flag = encoder.matches(userLoginVO.getPassword(), secret);
            if (flag) {
                return memberEntity;
            }
        }
        return null;
    }

    @Override
    public MemberEntity socialLogin(String json, GiteeSocialUser socialUser) {
        JSONObject map = JSONObject.parseObject(json);
        Long uid = map.getLong("id");
        String email = map.getString("email");
        String avatarUrl = map.getString("avatar_url");
        String name = map.getString("name");
        MemberEntity entity = new MemberEntity();
        //需要检查当前第三方id在member表中是否有绑定记录，有则更新access_token和expire_in，无则注册一条用户记录，信息可从第三方返回参数取
        MemberEntity memberEntity = this.getOne(new QueryWrapper<MemberEntity>().eq("uid", uid));
        if (memberEntity == null) {
            //新增第三方绑定记录
            entity.setUid(uid);
            entity.setAccessToken(socialUser.getAccessToken());
            entity.setExpireIn(socialUser.getExpiresIn());
            entity.setEmail(email);
            entity.setHeader(avatarUrl);
            entity.setUsername(name);
            entity.setNickname(name);
            entity.setCreateTime(new Date());
            this.save(entity);
            return entity;
        }else {
            //更新令牌信息
            memberEntity.setAccessToken(socialUser.getAccessToken());
            memberEntity.setExpireIn(socialUser.getExpiresIn());
            memberEntity.setCreateTime(null);
            this.updateById(memberEntity);
            return memberEntity;
        }
    }

    private void checkExistUsername(String username) throws UsernameExistException{
        int count = this.count(new QueryWrapper<MemberEntity>().eq("username", username));
        if (count > 0) {
            throw new UsernameExistException();
        }
    }

    private void checkExistPhone(String mobile) throws PhoneExistException{
        int count = this.count(new QueryWrapper<MemberEntity>().eq("mobile", mobile));
        if (count > 0) {
            throw new PhoneExistException();
        }
    }

}